package com.example.controller;

import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class ReadWriteLockController {

    @Autowired
    RedissonClient redissonClient;

    //加锁
    @GetMapping("/lock")
    public void getLock(){
        RLock rlock = redissonClient.getLock("rlock");
        try {
            String lockId = UUID.randomUUID().toString();
            //rlock.lock();
            rlock.lock(10L, TimeUnit.SECONDS);
            System.out.println(lockId + "加锁");
        } finally {
            rlock.unlock();
        }
    }

    //读写锁
    @GetMapping("/rlock")
    public void getRLock(){
        RReadWriteLock rReadWriteLock = redissonClient.getReadWriteLock("rwlock");
        RLock rLock = rReadWriteLock.readLock();
        try {
            rLock.lock();
            System.out.println("加读锁");
            Thread.sleep(5*1000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("释放读锁");
        }
    }

    @GetMapping("/wlock")
    public void getWLock(){
        RReadWriteLock rReadWriteLock = redissonClient.getReadWriteLock("rwlock");
        RLock wLock = rReadWriteLock.writeLock();
        try {
            wLock.lock();
            System.out.println("加写锁");
            Thread.sleep(5*1000);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            wLock.unlock();
            System.out.println("释放写锁");
        }
    }
}